//
//  UITestFileds.swift
//  EM68G
//
//  Created by godox on 2022/1/4.
//

import Foundation
import UIKit

extension UITextField {
    private struct RuntimeKey {
        static let jx_TextFieldKey = UnsafeRawPointer.init(bitPattern: "jx_TextField".hashValue)
        /// ...其他Key声明
    }
    /// 运行时关联
    public var jx: TextFieldTools {
        set {
            objc_setAssociatedObject(self, UITextField.RuntimeKey.jx_TextFieldKey!, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            var obj = objc_getAssociatedObject(self, UITextField.RuntimeKey.jx_TextFieldKey!) as? TextFieldTools
            if obj == nil { // 没有是手动创建 并进行绑定
                obj = TextFieldTools.init(self)
                objc_setAssociatedObject(self, UITextField.RuntimeKey.jx_TextFieldKey!, obj, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
            return obj!
        }
    }
    
    
    private struct PlaceholderColorKey {
        
        static var identifiter: String = "placeholderColorKey"
    }
    
    ///添加placeholderColor
    public var placeholderColor: UIColor {
        
        get {
            return objc_getAssociatedObject(self, &PlaceholderColorKey.identifiter) as! UIColor
        }
        
        set{
            objc_setAssociatedObject(self, &PlaceholderColorKey.identifiter, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            let attrString = NSMutableAttributedString(string: self.placeholder ?? "", attributes: [
                NSMutableAttributedString.Key.foregroundColor: newValue,
                NSMutableAttributedString.Key.font: UIFont.init(name: "PingFang SC", size: 12.0)!])
            self.attributedPlaceholder = attrString
        }
        
    }
    
}






public class TextFieldTools: NSObject, UITextFieldDelegate{
    
    
    /// 值改变回调
    public var valuesChangeBlock: ((String)->())?
    /// 结束编辑回调(未输入是不会回调)
    public var endEditingBlock: ((String)->())?
    /// 开始编辑
    public var beginEditingBlock:(()->())?

    private weak var tf: UITextField? // 定义属性用于临时记录
    
    convenience init(_ tf: UITextField) {
        self.init()
        self.tf = tf
        self.tf?.delegate = self
        self.tf!.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
    }
    @objc private func editingChanged() {
        if valuesChangeBlock == nil {return}
        valuesChangeBlock!(tf?.text ?? "")
    }
    
    override init() {
        super.init()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func textFieldDidEndEditing(_ textField: UITextField) {
        if endEditingBlock == nil {return}
        if (textField.text ?? "").isEmpty {return}
        endEditingBlock!(textField.text ?? "")
    }
    public func textFieldDidBeginEditing(_ textField: UITextField) {
        if beginEditingBlock == nil {return}
        beginEditingBlock!()
    }

    deinit {
        tf?.delegate = nil
    }
}
